package MergeSorting;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:归并排序
 * User: 均先生
 * Date: 2023-11-19
 * Time: 17:07
 */
public class MergeSorting {
    public static void mergeSort(int[] array) {
        mergeSortFun(array,0,array.length-1);
    }

    private static void mergeSortFun(int[] array, int start, int end) {
        if (start >= end) {
            return;
        }
        int mid = (start + end) / 2;
        mergeSortFun(array,start,mid);
        mergeSortFun(array,mid+1,end);
        merge(array,start,mid,end);
    }

    private static void merge(int[] array, int left, int mid, int right) {
        int s1 = left;
        int e1 = mid;
        int s2 = mid+1;
        int e2 = right;
        int[] tmpArr = new int[right-left+1];
        int k = 0;//tmpArr数组的下标
        while (s1 <= e1 && s2 <= e2) {//将分组数据排好序放入tmpArr
            if (array[s1] <= array[s2]) {
                tmpArr[k++] = array[s1++];
            }else {
                tmpArr[k++] = array[s2++];
            }
        }
        while (s1 <= e1) {
            tmpArr[k++] = array[s1++];
        }
        while (s2 <= e2) {
            tmpArr[k++] = array[s2++];
        }
        //将排好序的数组拷贝回原来的数组
        for (int i = 0; i < tmpArr.length; i++) {
            array[i+left] = tmpArr[i];
        }
    }

    public static void main(String[] args) {
        int[] array = {3,7,4,6,9,2,5};
        System.out.println("分组前:"+ Arrays.toString(array));
        mergeSort(array);
        System.out.println("分组后:"+ Arrays.toString(array));
    }
}
